# coding:utf-8
# py2
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
from __future__ import print_function
import sys

sys.path.append('/Users/lingzhengxin/workspace/python/Gunbaster')
sys.path.append('..')

reload(sys)
sys.setdefaultencoding('utf-8')
import hashlib
import json
import time
import urllib
import urllib2
import zlib

import requests

# 上一集付费标识位，用以过滤首集付费集狂欢弹幕
last_payed_flag = 0


def md5(params):
    appsecret = '*'
    s_param = sorted(params.items(), key=lambda d: d[0], reverse=False)
    sign_str = ''
    for p in s_param:
        sign_str += (p[0] + "=" + urllib.quote(str(p[1]), safe='') + "&")

    sign = sign_str[0:-1] + appsecret

    m = hashlib.md5()
    m.update(sign.encode('utf-8'))
    params['sign'] = m.hexdigest()
    return params


def convert_cid(epid=None, season_id=None):
    params = {
        'appkey': '*',
        'ts': int(time.time()),
        'mobi_app': 'android',
    }
    if season_id == None:
        params['ep_id'] = epid
    else:
        params['season_id'] = season_id
    signed_param = md5(params)
    season = requests.get("http://api.bilibili.com/pgc/view/app/season", signed_param)
    print(season.text)
    response = json.loads(season.text)
    index = 1
    eps = []
    for episode in response['result']['episodes']:
        if season_id == None:
            if episode[u'id'] == epid:
                print('所查ep：%s' % episode[u'share_copy'])
                print("epid对应的cid：<%s>" % episode[u'cid'])
                return {'cid': episode[u'cid'], 'index': episode[u'title'], 'badge': episode[u'badge']}
        else:
            eps.append({'cid': episode[u'cid'], 'index': episode[u'title'], 'badge': episode[u'badge']})
        index += 1
    return eps


def count_ep_dense(cid, seconds, badge, filtered_key_word=None):
    if filtered_key_word is None:
        filtered_key_word = []
    print('https://api.bilibili.com/x/v1/dm/list.so?oid=%s' % cid)
    request = urllib2.Request('https://api.bilibili.com/x/v1/dm/list.so?oid=%s' % cid)
    response = urllib2.urlopen(request)
    compresseddata = response.read()
    data = zlib.decompress(compresseddata, -zlib.MAX_WBITS)
    danmaku = str(data).split('<d p="')

    times = []
    global last_payed_flag
    for i in range(len(danmaku)):
        if i == 0:
            continue
        # 关键字过滤
        flag = 0
        for word in filtered_key_word:
            if word in danmaku[i]:
                print('filterd danmaku %s' % danmaku[i])
                flag = 1
                break
        if flag == 1:
            continue
        # 时间轴过滤
        try:
            danmuku_seconds = float(danmaku[i][0:6])
            # 首集付费ep过滤前一分钟狂欢弹幕
            if last_payed_flag == 0 and len(badge) > 0:
                # 番剧 op/ed 过滤
                # if (int(danmuku_seconds) < 4 * 60 or int(danmuku_seconds) > 21 * 60):
                if (int(danmuku_seconds) < 60):
                    print('drop danmaku:' + danmaku[i])
                    continue
            times.append(int(danmuku_seconds * 100))
        except ValueError as e:
            print(e)

    if len(badge) > 0:
        last_payed_flag = 1

    times.sort()
    max_count = 0
    min_count = 9999
    dense_danmaku = []
    sparse_danmaku = []
    for i in range(len(times)):
        count = 0
        count_danmaku = []
        if times[-1] - times[i] < seconds * 100:
            break
        for j in range(i, len(times)):
            if times[j] - times[i] > seconds * 100:
                count += 1
                count_danmaku.append(times[j])
                break
            count += 1
            count_danmaku.append(times[j])
        if count > max_count:
            max_count = count
            dense_danmaku = count_danmaku
        if count < min_count:
            min_count = count
            sparse_danmaku = count_danmaku
    print('top弹幕密度所在弹幕区间：%s分%s秒到%s分%s秒' % (str(dense_danmaku[0] / 6000), str(dense_danmaku[0] % 6000 / 100), str(
        dense_danmaku[-1] / 6000), str(dense_danmaku[-1] % 6000 / 100)))
    print('mine弹幕密度所在弹幕区间：%s分%s秒到%s分%s秒' % (str(sparse_danmaku[0] / 6000), str(sparse_danmaku[0] % 6000 / 100), str(
        sparse_danmaku[-1] / 6000), str(sparse_danmaku[-1] % 6000 / 100)))
    print("该ep%s秒范围top区间内的总弹幕量为：%s" % (seconds, max_count))
    print("该ep%s秒范围mine区间内的总弹幕量为：%s" % (seconds, min_count))
    start_time = dense_danmaku[0] + 0 * 100
    print('ffmpeg_param:-ss %s:%s:%s -t %s' % (str(start_time / (60 * 60 * 100)),
                                               str(start_time % (60 * 60 * 100) / 6000),
                                               str(start_time % 6000 / 100),
                                               seconds))
    return '-ss %s:%s:%s -t %s' % (str(start_time / (60 * 60 * 100)),
                                   str(start_time % (60 * 60 * 100) / 6000),
                                   str(start_time % 6000 / 100),
                                   seconds)
    # sys.exit('-ss %s:%s:%s -t %s' % (str(dense_danmaku[0] / (60 * 60 * 100)),
    #               str(dense_danmaku[0] % (60 * 60 * 100) / 6000),
    #                   str(dense_danmaku[0] % 6000 / 100),
    #                   seconds))

# if __name__ == '__main__':
#     epid = int(sys.argv[1])
#     print "epid:%s" % epid
#     # epid = 259772
#     # epid = 267858
#     density_seconds = int(sys.argv[2])
#     print "density_seconds:%s" % density_seconds
#     # density_seconds = 10
#     # epid转cid
#     cid = convert_cid(epid)
#     # 调用弹幕列表接口计算n秒内的最高弹幕密度
#     count_ep_dense(cid, density_seconds)
#
#     # 根据cid下载视频
#     vedio_path = '/Users/lingzhengxin/Documents/%s.mp4' % epid
#     result = get_download_list(cid)
#     # 取下载清晰度最高的mp4视频的url地址
# largest_format_index = 0
# index = 0
# for info in result[u'info']:
#     if info[u'format'] > largest_format_index:
#         largest_format_index = index
#     index += 1
# download_url = result[u'info'][largest_format_index][u'url']
# download_mp4(cid, download_url, vedio_path)
